import axios from 'axios'
import { HttpCode, LangApiHeader } from '@/enums'
import { useAccountStore, useAppStore } from '@/store'
import { ResType } from '@/types'
declare module 'axios' {
	interface AxiosInstance {
		(config: AxiosRequestConfig): Promise<any>
	}
}

const service = axios.create({
	baseURL: import.meta.env.VITE_BASE_API,
	timeout: 1000 * 60,
	withCredentials: true
})

service.defaults.headers.post['Content-Type'] = 'application/json'

// request interceptor
service.interceptors.request.use(
	(config: any) => {
		// do something before request is sent
		const accountStore = useAccountStore()
		const appStore = useAppStore()
		const defaultHeaders = <Record<string, string>>{
			lang: LangApiHeader[appStore.lang]
		}
		if (accountStore.token) {
			defaultHeaders.authorization = `Bearer ${accountStore.token}`
		}
		config.headers = { ...defaultHeaders, ...config.headers }
		return config
	},
	(error) => {
		// do something with request error
		return Promise.reject(error)
	}
)
// 响应拦截器
service.interceptors.response.use(
	(response: any) => {
		if (response.data instanceof Blob) {
			return response.data
		}
		const { code, msg, data } = response.data
		//   要根据success的成功与否决定下面的操作
		const resData: ResType = { data, code, msg }
		if (code === HttpCode.Success || code === HttpCode.GamesSuccess) {
			return resData
		} else {
			console.debug(response.config.url, resData)
			if (code === HttpCode.TokenError) {
				const accountStore = useAccountStore()
				accountStore.clearLoginInfo()
			} else if (code === HttpCode.UserForbiddenError) {
				// store.commit('user/forbidden')
			} else if (!Object.values(HttpCode).includes(code)) {
				// 	resData.code = HttpCode.Unknown
			}
			return Promise.reject(resData)
		}
	},
	(err) => {
		// const resData: ResType = {
		// 	code: HttpCode.Network,
		// 	data: response.data
		// }
		return Promise.reject(err.response.data)
	}
)

export default {
	post(url: any, param: any) {
		return new Promise((resolve, reject) => {
			service
				.post(url, param)
				.then((response) => {
					resolve(response)
				})
				.catch((thrown) => {
					reject(thrown)
				})
		})
	}
}
